package com.security.config.mobile;

import com.security.config.filter.SecurityFailureHandler;
import com.security.config.filter.SecuritySuccessHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 用户组合其他关于手机登录的组件
 */
@Component
public class MobileAuthenticationConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Resource
    UserDetailsService mobileUserDetailsService;

    @Resource
    SecurityFailureHandler securityFailureHandler;

    @Resource
    SecuritySuccessHandler securitySuccessHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        MobileAuthenticationFiler mobileAuthenticationFiler = new MobileAuthenticationFiler();
        mobileAuthenticationFiler.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        mobileAuthenticationFiler.setRememberMeServices(http.getSharedObject(RememberMeServices.class));
        mobileAuthenticationFiler.setAuthenticationSuccessHandler(securitySuccessHandler);
        mobileAuthenticationFiler.setAuthenticationFailureHandler(securityFailureHandler);
        MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider();
        mobileAuthenticationProvider.setService(mobileUserDetailsService);
        http.authenticationProvider(mobileAuthenticationProvider)
                .addFilterAfter(mobileAuthenticationFiler, UsernamePasswordAuthenticationFilter.class);
    }
}
